package com.ict.ms.trackPlayBack.facade.common; /**
 * Created by chitanda on 2017/10/27.
 */

import com.vividsolutions.jts.geom.Coordinate;
import org.geotools.geometry.GeometryFactoryFinder;
import org.geotools.gml3.Circle;
import org.opengis.geometry.coordinate.GeometryFactory;


public class CircleWithLongitudeCrossed180 {
    private static GeometryFactory geometryFactory = GeometryFactoryFinder.getGeometryFactory( null );
    protected Circle circle = null;
    private Boolean is180LongitudeCrossed = false;

    CircleWithLongitudeCrossed180(double Longitude, double Latitude, double radiusInMeters){


        Coordinate center = new Coordinate(Longitude,Latitude);
        if(!checkPointFValidity(center)){
            throw new IllegalArgumentException(String.format("Invalid points:<%f,%f>",center.x,center.y));
        }
        circle = CircleWithLongitudeCrossed180.createCircle(center, radiusInMeters);
    }


    public boolean containsPoint(double lon,double lat){


        //两点之间的距离小于半径即在圆形区域内
        if(distenceFromCenter(lon,lat) < circle.getRadius()){
            return true;
        }else{
            return false;
        }
    }

    public double distenceFromCenter(double lon,double lat){

        Coordinate center = circle.getCenter();
        return distenceOf2Point(lon,lat,center.x,center.y);

    }

    public double distenceOf2Point(double lon,double lat,double lonx,double laty){
        double rad;
        double lat1;
        double lat2;
        double a;
        double distance;
        int R=6371000;//地球半径


        rad=Math.PI/180;
        lat1=lat*rad;
        lat2=laty*rad;

        a=Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos((lonx-lon)*rad);
        distance=R*Math.acos((Math.min(a,1)));
        return distance;
    }



    /**
     * 根据圆心和半径创建圆
     * @return
     */
    private static Circle createCircle(Coordinate center, double radius){
        return new Circle(center,radius);
    }





    private boolean checkPointFValidity(Coordinate p){
        if(p.x<-180||p.x>180||p.y>90||p.y<-90)
        {
            System.out.println(String.format("Invalid points:<%f,%f>",p.x,p.y));
            return false;
        }
        return true;
    }






}
